package com.bfly.mall.advert.controller;

import com.bfly.common.ResponseUtil;
import com.bfly.common.page.Pager;
import com.bfly.common.util.DataConvertUtils;
import com.bfly.core.base.controller.BaseController;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.context.PagerThreadLocal;
import com.bfly.core.enums.SysError;
import com.bfly.core.exception.ServiceResponseException;
import com.bfly.core.security.ActionModel;
import com.bfly.mall.advert.dto.CouponFormDTO;
import com.bfly.mall.advert.dto.CouponGetRecordUserListDTO;
import com.bfly.mall.advert.dto.CouponListDTO;
import com.bfly.mall.advert.dto.CouponProductNamesDTO;
import com.bfly.mall.advert.entity.Coupon;
import com.bfly.mall.advert.entity.CouponRangeBind;
import com.bfly.mall.advert.enums.CouponStatus;
import com.bfly.mall.advert.enums.CouponUseRange;
import com.bfly.mall.advert.service.ICouponGetRecordService;
import com.bfly.mall.advert.service.ICouponService;
import com.bfly.mall.product.entity.Product;
import com.bfly.mall.product.entity.ProductCategory;
import com.bfly.mall.product.service.IProductCategoryService;
import com.bfly.mall.product.service.IProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 优惠卷
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/9/20 13:33
 */
@RestController
@RequestMapping(value = "/manage/coupon")
public class CouponController extends BaseController {

    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICouponGetRecordService getRecordService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductCategoryService categoryService;

    /**
     * 优惠卷列表
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/18 22:48
     */
    @GetMapping(value = "/list")
    public void list(HttpServletResponse response, HttpServletRequest request) {
        PagerThreadLocal.set(request);
        String status = request.getParameter("status");
        String range = request.getParameter("range");
        String name = request.getParameter("name");

        Map<String, Object> exact = new HashMap<>(2);
        Map<String, String> unExact = new HashMap<>(1);
        if (StringUtils.isNotBlank(status)) {
            exact.put("status", DataConvertUtils.convertToInteger(status));
        }
        if (StringUtils.isNotBlank(range)) {
            exact.put("use_range", range);
        }
        if (StringUtils.isNotBlank(name)) {
            unExact.put("name", name);
        }

        Pager<Coupon> pager = couponService.getPage(exact, unExact, null);
        Pager<CouponListDTO> dtoPager = new Pager<>(pager.getPageNo(), pager.getPageSize(), pager.getTotalCount());

        if (pager.getData() != null) {
            List<CouponListDTO> list = new ArrayList<>();
            for (Coupon coupon : pager.getData()) {
                List<CouponProductNamesDTO> couponProductNamesDTOList = new ArrayList<>();
                CouponListDTO dto = new CouponListDTO();
                BeanUtils.copyProperties(coupon, dto);

                if (coupon.getUseRange() == CouponUseRange.ALL.getId()) {
                    CouponProductNamesDTO namesDTO = new CouponProductNamesDTO();
                    namesDTO.setName(CouponUseRange.ALL.getName());
                    couponProductNamesDTOList.add(namesDTO);
                    dto.setCouponProductNames(couponProductNamesDTOList);
                    list.add(dto);
                    continue;
                }
                List<CouponRangeBind> couponRangeBind = coupon.getCouponRangeBinds();
                List<Integer> listId = couponRangeBind.stream().map(cg -> cg.getRangeId()).collect(Collectors.toList());
                Integer[] rangeId = new Integer[listId.size()];
                rangeId = listId.toArray(rangeId);

                Map<String, Object> param = new HashMap<>(1);
                param.put("id_in", rangeId);

                if (coupon.getUseRange() == CouponUseRange.CATEGORY.getId()) {
                    List<ProductCategory> categories = categoryService.getList(param);
                    categories.forEach(category -> {
                        CouponProductNamesDTO namesDTO = new CouponProductNamesDTO();
                        namesDTO.setName(category.getName());
                        namesDTO.setId(category.getId());
                        couponProductNamesDTOList.add(namesDTO);
                    });
                } else if (coupon.getUseRange() == CouponUseRange.PRODUCT.getId()) {
                    List<Product> products = productService.getList(param);
                    products.forEach(good -> {
                        CouponProductNamesDTO namesDTO = new CouponProductNamesDTO();
                        namesDTO.setName(good.getName());
                        namesDTO.setId(good.getId());
                        couponProductNamesDTOList.add(namesDTO);
                    });
                }
                dto.setCouponProductNames(couponProductNamesDTOList);
                list.add(dto);
            }
            dtoPager.setData(list);
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(dtoPager));
    }

    /**
     * 新增优惠卷
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/20 12:24
     */
    @PostMapping(value = "/add")
    @ActionModel(value = "新增优惠卷")
    public void saveCoupon(HttpServletResponse response, @Valid @RequestBody CouponFormDTO formDTO, BindingResult result) {
        validData(result);
        couponService.save(formDTO);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 编辑优惠卷状态
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/20 12:24
     */
    @GetMapping(value = "/editStatus")
    @ActionModel(value = "编辑优惠卷状态")
    public void editCouponStatus(HttpServletResponse response, @RequestParam("couponId") int couponId, @RequestParam("status") int status) {
        CouponStatus couponStatus = CouponStatus.getStatus(status);
        if (couponStatus == null) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "状态参数不正确!");
        }
        if (status != CouponStatus.OFF_SHELF.getId() && status != CouponStatus.ON_SHELF.getId()) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "状态为" + couponStatus.getName() + " 的优惠卷不能修改状态!");
        }
        couponService.editStatus(couponId, couponStatus);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 编辑优惠卷
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/20 12:24
     */
    @PostMapping(value = "/edit")
    @ActionModel(value = "编辑优惠卷")
    public void editCoupon(HttpServletResponse response, @Valid @RequestBody CouponFormDTO formDTO, BindingResult result) {
        validData(result);
        couponService.edit(formDTO);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 删除优惠卷
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/9/20 12:26
     */
    @PostMapping(value = "/delete")
    @ActionModel(value = "删除优惠卷")
    public void removeCoupon(HttpServletResponse response, @RequestBody Integer... adIds) {
        couponService.remove(adIds);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 查询优惠卷的领卷记录
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/12/24 15:10
     */
    @GetMapping(value = "/getrecord")
    public void getCouponGetRecordForUser(HttpServletResponse response, HttpServletRequest request, @RequestParam("couponId") int couponId) {
        PagerThreadLocal.set(request);
        Pager<CouponGetRecordUserListDTO> pager = getRecordService.getCouponGetRecordForUser(couponId);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(pager));
    }
}